package com.lw.leetcode.sort.b;

import java.util.Arrays;
import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * sort
 * 1882. 使用服务器处理任务
 *
 * @author liw
 * @version 1.0
 * @date 2022/10/25 10:07
 */
public class AssignTasks {

    public static void main(String[] args) {
        AssignTasks test = new AssignTasks();

        // [2,2,0,2,1,2]
//        int[] servers = {3, 3, 2};
//        int[] tasks = {1, 2, 3, 2, 1, 2};

        // [1,4,1,4,1,3,2]
//        int[] servers = {5, 1, 4, 3, 2};
//        int[] tasks = {2, 1, 2, 4, 5, 2, 1};

        // [8, 0, 3, 9, 5, 1, 10, 6, 4, 2, 7, 9, 0]
        int[] servers = {10, 63, 95, 16, 85, 57, 83, 95, 6, 29, 71};
        int[] tasks = {70, 31, 83, 15, 32, 67, 98, 65, 56, 48, 38, 90, 5};

        int[] ints = test.assignTasks(servers, tasks);
        System.out.println(Arrays.toString(ints));
    }

    public int[] assignTasks(int[] servers, int[] tasks) {
        PriorityQueue<Long> queue = new PriorityQueue<>();
        PriorityQueue<Long> times = new PriorityQueue<>();
        int length = servers.length;
        int l = tasks.length;
        int[] arr = new int[l];
        for (int i = 0; i < length; i++) {
            queue.add(((long) servers[i] << 32) + i);
        }
        long time = 0;
        for (int i = 0; i < l; i++) {
            int task = tasks[i];
            time = Math.max(time, i);
            while (!times.isEmpty()) {
                long p = times.peek();
                if ( (int) (p >> 32) <= time) {
                    times.poll();
                    int index = (int) p;
                    queue.add(((long) servers[index] << 32) + index);
                } else {
                    break;
                }
            }
            if (queue.isEmpty()) {
                long p = times.poll();
                time = (int) (p >> 32);
                int index = (int) p;
                queue.add(((long) servers[index] << 32) + index);
                while (!times.isEmpty()) {
                    p = times.peek();
                    int t = (int) (p >> 32);
                    if (t == time) {
                        index = (int) p;
                        queue.add(((long) servers[index] << 32) + index);
                        times.poll();
                    } else {
                        break;
                    }
                }
            }
            int index = queue.poll().intValue();
            times.add(((time + task) << 32) + index);
            arr[i] = index;
        }
        return arr;
    }

}
